package drds.plus.executor.transaction.strict;


import drds.plus.datanode.api.Connection;
import drds.plus.datanode.api.DatasourceManager;
import drds.plus.executor.transaction.AbstractConnectionHolder;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;

import java.sql.SQLException;

/**
 * 不允许做任何跨库事务
 */
@Slf4j
public class StrictConnectionHolder extends AbstractConnectionHolder {
    public Logger log() {
        return log;
    }

    //
    private Connection connection = null;
    private boolean inUse = false;

    public StrictConnectionHolder() {

    }

    public Connection getConnection(String dataNodeId, DatasourceManager datasourceManager) throws SQLException {
        checkClosed();
        if (inUse) {
            throw new IllegalStateException("ERR_CONCURRENT_TRANSACTION" + dataNodeId);
        }
        inUse = true;
        //
        if (connection == null) {
            connection = datasourceManager.getConnection();
            connectionSet.add(connection);
        }
        return connection;

    }

    public void tryClose(String dataNodeId, Connection connection) throws SQLException {
        if (connection != this.connection) {
            throw new IllegalStateException("impossible");
        }
        inUse = false;
    }

    public void closeConnectionSet() {
        super.closeConnectionSet();
        this.connection = null;
    }

    public void cancel() {
        super.cancel();
        this.connection = null;
    }


}
